
#include "pict.h"



/* ----------------- start main section ----------------- */
extern MEMORY_MANAGEMENT * memman ;
extern int * fat12 ;
int readIMG (SHEET * sheet ) { 
	
	struct DLL_STRPICENV *env  = memman_alloc (memman,sizeof(struct DLL_STRPICENV));
	char *filebuf  ;
	struct RGB *picbuf = memman_alloc_4k(memman,1024*768 * sizeof(struct RGB)) ;
	struct RGB *q;
	int info[8] ,fsize; //存储文件信息
	int i=0,j ,k,l,m=0,n=0;
	int locx ,locy ;
	char * buf ;
	struct FILEINFO * file = file_search ("night_.bmp") ;
	//return file->size ;
	if (file <=0) { 
		return 1;
	}
	fsize = file->size ;
	filebuf=memman_alloc_4k(memman,512*1024) ;
	file_loadfile (file ,fat12 ,ADR_DISKIMG +0x003e00 ,filebuf) ;
	/**
		info[0] : 文件类型  v =1 BMP ,v =2 JPEG
		info[1] : 颜色数信息
		info[2] : xsize 
		info[3] : ysize
	*/
	if (info_BMP(&env ,info,fsize ,filebuf) ==0){ //不是BMP 
		
		if (info_JPEG(&env ,info,fsize ,filebuf) ==0){ //也不是jpeg
			return 10;
		} 
		
	}



	if(info[2] > 1024 || info[3] >768){ 
		return -2 ;
	}

	if (info[0] ==1) { 
		i = decode0_BMP(&env ,fsize ,filebuf,4,(char *)picbuf ,0);
	}else { 
		i = decode0_JPEG(&env ,fsize ,filebuf,4,(char *)picbuf ,0);
	}

	if (i != 0 ) { 
		return 3 ;
	}
	buf = sheet->buf ;
	

	m = sheet->bxsize /info[2] ;// 平铺 ，横着的个数
	if (sheet->bxsize % info[2] >0) { 
		m +=1 ;
	}
	n =  sheet->bysize /info[3] ;// 平铺 , 竖着的个数
	if (sheet->bysize %info[3] >0) {	
		n +=1 ;
	}
	for (k =0 ; k < n ;k++) { 
		for (l=0 ; l<m ;l++){ 
			for (i =0 ; i <info[3] ; i++) { 
			q = picbuf + info[2] *i ;
	//	buf  = sheet->buf + sheet->bxsize * i ;
				for (j = 0 ; j <info[2] ; j++) { 
			//buf[j] = rgb2pal (q[j].r,q[j].g,q[j].b ,j,i) ;
					locx = j+l*info[2] ;
					locy = i+k*info[3] ;
					if (locx < sheet->bxsize && locy <sheet->bysize) {
					sheet->buf[locx + sheet->bxsize *locy] = rgb2pal (q[j].r,q[j].g,q[j].b ,j,i) ;
					}
				}
			} 

		}
	}

	
		
	
	memman_free_4k(memman,env,sizeof(struct DLL_STRPICENV)) ;
	memman_free_4k(memman,picbuf ,sizeof(struct RGB) * 1024*768) ;
	memman_free_4k(memman,filebuf ,fsize) ;
	sheet_refresh_bysht(sheet) ;
	return 0 ;
}


